package com.bw.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.common.resp.ResponseResult;
import com.bw.entity.User;
import com.bw.service.IUserService;
import com.bw.utils.auth.JwtUtils;
import com.bw.utils.auth.RsaUtils;
import com.bw.utils.auth.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-05-29
 */
@RestController
@RequestMapping("user")
@CrossOrigin
public class UserController {
   //刘豪伟123
    @Autowired
    private IUserService userService;

    @PostMapping("login")
    public ResponseResult login(@RequestBody User user){
        ResponseResult result = ResponseResult.SUCCESS();
        try{

            QueryWrapper queryWrapper = new QueryWrapper();//条件选择器
            Map map =  new HashMap(); //往前台传两个参数 用map
            map.put("uname",user.getUname()); //存入map
            map.put("upwd",user.getUpwd());
            queryWrapper.allEq(map);

            User o = userService.getOne(queryWrapper);
            if(o!=null){
                //获取私钥
                PrivateKey privateKey = RsaUtils.getPrivateKey("D:\\1711A\\keys\\rsa.pri");
                UserInfo userInfo = new UserInfo();
                userInfo.setId(o.getUid());
                userInfo.setUsername(o.getUname());

                //生成令牌
                String token = JwtUtils.generateToken(userInfo,privateKey,30);
                Map mapinfo = new HashMap();
                mapinfo.put("user",user);
                mapinfo.put("token",token);

                result.setResult(mapinfo);
                result.setMessage("登录成功！");


            }else{
                result.setSuccess(false);
                result.setMessage("用户名或密码错误");
            }
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("登录失败"+e.toString());
        }
        return result;
    }
}
